import 'dart:convert';

import 'package:ble_demo/ble/ble_action_type.dart';
import 'package:ble_demo/ble/ble_device.dart';
import 'package:ble_demo/ble/ble_plugin.dart';
import 'package:ble_demo/entity/smart_device.dart';
import 'package:ble_demo/pages/device_display_data.dart';
import 'package:ble_demo/pages/user_help_page.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'ecg_device_display_data.dart';

/**
 * 心电图设备扫描页
 */
class EcgScanDevicePage extends StatefulWidget {
  SmartDevice smartDevice;

  EcgScanDevicePage(this.smartDevice);

  @override
  State<StatefulWidget> createState() => EcgScanDevicePageState();
}

class EcgScanDevicePageState extends State<EcgScanDevicePage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  //标记是否是扫描中
  bool isScanning = true;


  //显示标题
  String title = "附近的蓝牙设备";
  //动画控制器
  AnimationController _controller;
  //设备本地存储器
  Future<SharedPreferences> _device_prefs = SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    //动画初始化
    _controller =
        AnimationController(vsync: this, duration: Duration(seconds: 15));

    //初始化sdk
    BlePlugin.initBleHeartSdk();

    /// ble监听初始化
    BlePlugin.addListener(onBleListener);
    //设备广播过滤
    BlePlugin.initBleHeartScanRule(deviceName: widget.smartDevice.name,scanTimeOut: 5000);
    _controller.forward();
    //开始扫描
    BlePlugin.startHeartScan();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      if (isScanning) {
        _controller.forward();
        BlePlugin.startHeartScan();
      }
    } else if (state == AppLifecycleState.paused) {
      if(isScanning){
        _controller.stop();
        BlePlugin.cancelScan();
      }
    }
  }

  Future<bool> _localStoreDevice(String mac) async {
    final SharedPreferences prefs = await _device_prefs;
    return prefs.containsKey(mac);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xffeeeeee),
        appBar: AppBar(
            leading: IconButton(
              icon: Icon(
                Icons.chevron_left,
                color: Color(0xff222222),
                size: 24,
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            centerTitle: true,
            title: Text(
              title,
              style: TextStyle(color: Color(0xff222222)),
            )),
        body: _buildScanningWidget(context));
  }

  /**
   * 扫描组件
   */
  _buildScanningWidget(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
                padding: const EdgeInsets.only(top: 10, bottom: 5),
                child: RotationTransition(
                  turns: _controller
                    ..addStatusListener((status) {
                      if (status == AnimationStatus.completed) {
                        _controller.reset();
                        _controller.forward();
                      }
                    }),
                  child: Image.asset("assets/images/img_radar.png",
                      fit: BoxFit.contain),
                )),
            Padding(
                padding: const EdgeInsets.only(top: 15, bottom: 5),
                child: Text("请靠近无线心电仪设备",
                  style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                )),
            Padding(
                padding: const EdgeInsets.only(top: 15, bottom: 5),
                child: Text(
                  "请确认手机设备已开启且在附近",
                  style: TextStyle(color: Colors.black12),
                )),
            if (!isScanning) _buildItemEmptyResult(context),
            Padding(
                padding: const EdgeInsets.only(top: 30, bottom: 10),
                child: FlatButton(
                  onPressed: () {
                    BlePlugin.cancelScan();
                    Navigator.of(context).pop();
                  },
                  child: Text("取消",
                      style: TextStyle(color: Colors.black45, fontSize: 16)),
                )),
          ],
        ),
      ),
    );
  }

  /**
   * 未扫描到任何设备
   */
  _buildItemEmptyResult(context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Padding(
            padding: const EdgeInsets.only(top: 15, bottom: 10),
            child: GestureDetector(
              child: Text(
                "扫描不到怎么办？",
                style: TextStyle(
                    fontSize: 18, decoration: TextDecoration.underline,color: Colors.blue),
              ),
              onTap: () {
                Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) => UserHelpPage()));
              },
            )),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10.0)),
            border: new Border.all(width: 1, color: Colors.blue),
          ),
          width: 240,
          height: 48,
          child: FlatButton(
              onPressed: () {
                setState(() {
                  isScanning = true;
                });
                _controller.forward();
                Future.delayed(Duration(seconds: 2), () {
                  BlePlugin.startHeartScan();
                });
              },
              child: Text(
                "重新扫描",
                style: TextStyle(color: Colors.blue, fontSize: 18),
              )),
        )
      ],
    );
  }

  /// 销毁
  @override
  dispose() {
    WidgetsBinding.instance.removeObserver(this);
    BlePlugin.removeListener(onBleListener);
    _controller.dispose();
    super.dispose();
  }

  //回调
  onBleListener(type, params) {
    print("type==$type,params=$params");
    //设备启动扫描开始
    if (type == BleActionType.ONHEARTSCANSTARTED) {

    } //扫描到符合设置扫描规则的回调
    else if (type == BleActionType.ONHEARTSCANFINISHED) {
      List deviceList = jsonDecode(params)["deviceList"];
      print("deviceList==$deviceList");
      if (deviceList != null && deviceList.length > 0) {
        _localStoreDevice(deviceList[0]["name"]).then((isStoreLocal) {
          Navigator.of(context).pushReplacement(MaterialPageRoute(
              builder: (context) => EcgDeviceDisplayData(SmartDevice(
                  name: deviceList[0]["name"],
                  mac:deviceList[0]["bleDevice"]["mac"],
                  isStoreLocal: isStoreLocal))));
        });

      } else {
        //停止动画
        _controller.stop();
        setState(() {
          isScanning = false;
          title = "未发现待连接的蓝牙设备";
        });
      }
    }
  }
}
